from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime

from db_models import UserDB, TodoDB
from models import User, UserRole, TodoCreate, Todo
from auth import get_password_hash

class UserService:
    """
    用户管理服务层
    封装用户相关的数据库操作
    """
    
    @staticmethod
    def get_all_users(db: Session) -> List[UserDB]:
        """
        获取所有用户（管理员功能）
        """
        return db.query(UserDB).order_by(UserDB.created_at.asc()).all()
    
    @staticmethod
    def get_user_by_id(db: Session, user_id: int) -> Optional[UserDB]:
        """
        根据ID获取用户
        """
        return db.query(UserDB).filter(UserDB.id == user_id).first()
    
    @staticmethod
    def create_user(db: Session, username: str, password: str, role: UserRole = UserRole.USER) -> UserDB:
        """
        创建新用户
        """
        password_hash = get_password_hash(password)
        db_user = UserDB(username=username, password_hash=password_hash, role=role)
        db.add(db_user)
        db.commit()
        db.refresh(db_user)
        return db_user
    
    @staticmethod
    def get_user_todos(db: Session, user_id: int) -> List[TodoDB]:
        """
        获取用户的所有待办事项
        """
        return db.query(TodoDB).filter(TodoDB.user_id == user_id).order_by(TodoDB.order.asc()).all()
    
    @staticmethod
    def convert_to_pydantic(db_user: UserDB) -> User:
        """
        将数据库模型转换为 Pydantic 模型
        """
        return User(
            id=db_user.id,
            username=db_user.username,
            role=db_user.role,
            created_at=db_user.created_at,
            updated_at=db_user.updated_at
        )

class AdminService:
    """
    管理员专用服务层
    """
    
    @staticmethod
    def assign_todo_to_user(db: Session, admin_user: UserDB, todo_data: TodoCreate, target_user_id: int) -> TodoDB:
        """
        管理员为指定用户分配任务
        """
        # 获取用户当前最大的 order 值
        max_order = db.query(TodoDB.order).filter(
            TodoDB.user_id == target_user_id
        ).order_by(TodoDB.order.desc()).first()
        next_order = (max_order[0] + 1) if max_order and max_order[0] is not None else 0
        
        # 创建数据库实例（标记为管理员分配）
        db_todo = TodoDB(
            user_id=target_user_id,
            title=todo_data.title,
            description=todo_data.description,
            status=todo_data.status,
            priority=todo_data.priority,
            order=next_order,
            assigned_by_admin=True  # 标识为管理员分配
        )
        
        # 保存到数据库
        db.add(db_todo)
        db.commit()
        db.refresh(db_todo)
        
        return db_todo
    
    @staticmethod
    def get_all_todos(db: Session) -> List[TodoDB]:
        """
        获取系统中所有待办事项（管理员功能）
        """
        return db.query(TodoDB).order_by(TodoDB.user_id.asc(), TodoDB.order.asc()).all()
    
    @staticmethod
    def get_user_statistics(db: Session) -> dict:
        """
        获取用户统计信息（管理员功能）
        """
        total_users = db.query(UserDB).count()
        admin_users = db.query(UserDB).filter(UserDB.role == UserRole.ADMIN).count()
        regular_users = db.query(UserDB).filter(UserDB.role == UserRole.USER).count()
        total_todos = db.query(TodoDB).count()
        
        return {
            "total_users": total_users,
            "admin_users": admin_users,
            "regular_users": regular_users,
            "total_todos": total_todos
        }